<template>
  <x-layout-main>
    <div>
      <div class="g-content pb-0">
        <x-form ref="formRef" v-model:model="form" inline wrap label-placement="left">
          <n-form-item label="媒体账户">
            <n-select
              v-model:value="form.accountCode"
              size="small"
              placeholder="请选择"
              :options="accountOwnerList"
              filterable
              clearable
            />
          </n-form-item>
          <n-form-item label="所属人员">
            <n-select
              v-model:value="form.accountId"
              label-field="accountName"
              value-field="accountId"
              size="small"
              placeholder="请选择"
              :options="accountList"
              filterable
              clearable
            />
          </n-form-item>
          <n-form-item>
            <n-date-picker
              v-model:value="form.dateRange"
              size="small"
              type="daterange"
              :is-date-disabled="disablePreviousDate"
              style="margin-right: 10px"
            />
            <x-button size="small" type="primary" @click="handleSubmit">查询</x-button>
            <x-button size="small" @click="handleRefresh">重置</x-button>
          </n-form-item>
        </x-form>
      </div>
      <div class="g-content">
        <div>
          <x-data-table
            ref="tableRef"
            v-model:immediate="immediate"
            :params="paginationParams"
            :columns="columns"
            :scroll-x="TableScrollX"
            :row-key="(row) => row.id"
            :export-action="exportAction"
            :export-name-prefix="exportName"
            :summary="summary"
            row-class-name="text-sm"
            max-height="infinite"
            @update:sorter="handleSorterChange"
          >
            <template #tableTitle>
              <div class="flex">
                <div style="flex: 1"></div>
                <x-diy-column-draggable
                  :key="diyColumnName"
                  v-model:value="showColumnList"
                  :button-size="'small'"
                  :name="diyColumnName"
                  :min="0"
                  api="dictionary/columnList"
                  :api-params="diyColumnParams"
                />
              </div>
            </template>
          </x-data-table>
        </div>
      </div>
    </div>
  </x-layout-main>
</template>

<script setup lang="ts">
  import { ref, computed, h, onMounted } from 'vue'
  import { XForm, XButton, XDataTable, XDiyColumnDraggable } from '@/components'
  import { NFormItem, NSelect, NSpace, NText, NDatePicker } from 'naive-ui'
  import { useRouter } from 'vue-router'
  import { useStore } from '@/store'
  import { formatDate } from '@/utils'
  import XLayoutMain from '@/components/x-layout-main/index.vue'
  import { gdtAccountOwnerList } from '@/api/intelligent'
  import { startOfDay } from 'date-fns'

  const router = useRouter()
  const store = useStore()
  const props = defineProps({})
  const tableRef = ref(null)
  const formRef = ref(null)
  const form = ref({
    order: '',
    desc: null,
    accountCode: null,
    accountId: null,
    dateRange: [
      new Date(new Date().setDate(new Date().getDate() - 1)),
      new Date(new Date().setDate(new Date().getDate() - 1))
    ]
  })
  const accountOwnerList = ref([])
  const accountList = ref([])
  const summaryDate = ref({})
  const immediate = ref(true)
  const diyColumnParams = ref({
    key: 'FUND_TYPE_REPORT'
  })
  // 自定义列
  const showColumnList = ref([])
  const diyColumnName = computed(() => {
    return 'FUND_TYPE_REPORT'
  })
  const paginationParams = computed(() => {
    return {
      actions: 'report/fundTypeReports',
      data: {
        ...form.value,
        dateRange: null,
        dateRange1: null,
        startDate: form.value.dateRange ? formatDate(form.value.dateRange?.[0]) : null,
        endDate: form.value.dateRange ? formatDate(form.value.dateRange?.[1]) : null,
        columns: showColumnList.value?.toString()
      }
    }
  })
  const disablePreviousDate = (ts: number, type: string, range: number[] | null) => {
    if (startOfDay(ts).valueOf() > startOfDay(new Date()).valueOf() - 86400000) {
      return true
    }
    if (type === 'start' && range !== null) {
      return startOfDay(range[1]).valueOf() - startOfDay(ts).valueOf() > 86400000 * (31 - 1)
    }
    if (type === 'end' && range !== null) {
      return startOfDay(ts).valueOf() - startOfDay(range[0]).valueOf() > 86400000 * (31 - 1)
    }
    return false
  }
  const exportAction = computed(() => 'report/fundTypeReportsExport')
  const exportName = computed(() => {
    return `【财务管理】${formatDate(new Date(), 'yyyyMMddhhmmss')}`
  })
  const columns = computed(() => {
    const arr = [
      {
        title: '日期',
        width: 100,
        key: 'reportDate'
      },
      {
        title: '账户名称',
        key: 'accountName',
        width: 100,
        render(row: any) {
          return h(NSpace, { vertical: true }, () => [
            h(NText, {}, () => row.accountName),
            h(NText, {}, () => `ID:${row.accountCode}`)
          ])
        }
      },
      {
        title: '所属人员',
        key: 'ownerName',
        width: 100
      },
      {
        title: '资金账户类型',
        key: 'fundType',
        width: 120
      },
      {
        title: '总存入（元）',
        key: 'deposit',
        sorter: true,
        width: 120
      },
      {
        title: '总支出（元）',
        key: 'paid',
        sorter: true,
        width: 120
      },
      {
        title: '总转入（元）',
        key: 'transIn',
        sorter: true,
        width: 120
      },
      {
        title: '总转出（元）',
        key: 'transOut',
        sorter: true,
        width: 120
      },
      {
        title: '授信调整',
        key: 'creditModify',
        sorter: true,
        width: 100
      },
      {
        title: '日终结余（元）',
        key: 'balance',
        sorter: true,
        width: 120
      },
      {
        title: '锁定剩余（元）',
        key: 'preauthBalance',
        sorter: true,
        width: 120
      }
    ]
    const sortArr = []
    showColumnList.value.forEach((item) => {
      arr.forEach((item2) => {
        if (item === item2.key) {
          sortArr.push(item2)
        }
      })
    })
    return sortArr.filter((item) => ['selection', 'switch', ...showColumnList.value].includes(item.key))
  })
  const TableScrollX = computed(() => {
    let x = 20
    columns.value.forEach((item) => {
      if (item.type === 'expand') {
        x += 30
      }
      if (item.type === 'selection') {
        x += 30
      }
      if (item.width) {
        x += item.width
      }
    })
    return x
  })

  const summary = (pageData: any) => {
    const summaryDate1 = summaryDate.value
    return {
      reportDate: {
        value: h('span', { style: { color: 'red' } }, '总计')
      },
      accountName: {
        value: h('span', { style: { color: 'red' } }, '-')
      },
      ownerName: {
        value: h('span', { style: { color: 'red' } }, '-')
      },
      fundType: {
        value: h('span', { style: { color: 'red' } }, '-')
      },
      deposit: {
        value: h('span', { style: { color: 'red' } }, summaryDate1.deposit)
      },
      paid: {
        value: h('span', { style: { color: 'red' } }, summaryDate1.paid)
      },
      transIn: {
        value: h('span', { style: { color: 'red' } }, summaryDate1.transIn)
      },
      transOut: {
        value: h('span', { style: { color: 'red' } }, summaryDate1.transOut)
      },
      creditModify: {
        value: h('span', { style: { color: 'red' } }, summaryDate1.creditModify)
      },
      balance: {
        value: h('span', { style: { color: 'red' } }, summaryDate1.balance)
      },
      preauthBalance: {
        value: h('span', { style: { color: 'red' } }, summaryDate1.preauthBalance)
      }
    }
  }

  onMounted(() => {
    gdtAccountOwnerList()
    getAccountList()
    getSummaryData()
  })

  function handleSorterChange(options: { order: string | number | boolean; columnKey: string }) {
    const sortKey: any = {
      descend: 'desc',
      ascend: 'asc'
    }
    form.value.order = options?.columnKey
    form.value.desc = options.order ? sortKey[options.order] : null
    handleSubmit()
  }

  const handleSubmit = () => {
    immediate.value = true
    getSummaryData()
  }
  const gdtAccountOwnerList = () => {
    store
      .dispatch('intelligent/gdtAccountOwnerList', {
        pageSize: 10000
      })
      .then(({ data }) => {
        const list: { value: any; label: any }[] = []
        data.forEach((item: any) => {
          list.push({
            value: item,
            label: item
          })
        })
        accountOwnerList.value = list
      })
  }
  const getAccountList = () => {
    store
      .dispatch('system/accountList', {
        pageSize: 10000
      })
      .then(({ data }) => {
        accountList.value = data
      })
  }
  const getSummaryData = () => {
    const params = {
      ...form.value,
      dateRange: null,
      dateRange1: null,
      startDate: form.value.dateRange ? formatDate(form.value.dateRange?.[0]) : null,
      endDate: form.value.dateRange ? formatDate(form.value.dateRange?.[1]) : null
    }
    store.dispatch('report/fundTypeReportsTotal', params).then(({ data }) => {
      summaryDate.value = data
    })
  }
  const handleRefresh = () => {
    formRef.value.resetFields()
    handleSubmit()
  }
</script>

<style lang="scss" scoped></style>
